package com.one.group.admin.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.one.group.admin.mapper.NoticeMapper;
import com.one.group.model.dto.InsertNoticeDto;
import com.one.group.model.dto.NoticeQueryDto;
import com.one.group.model.dto.UpdateNoticeDto;
import com.one.group.model.entity.Notice;
import com.one.group.model.vo.NoticeListVo;
import com.one.group.service.NoticeService;
import com.one.group.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author kld
 * @date 2025/9/28 15:10
 * @description 公告
 */
@DubboService
@Slf4j
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements NoticeService {



    @Override
    public void saveByDto(InsertNoticeDto insertNoticeDto) {
        Notice notice = new Notice();
        BeanUtils.copyProperties(insertNoticeDto, notice);
        log.debug("新增数据：{}", insertNoticeDto);
        log.debug("新增数据：{}", notice);
        this.save(notice);
    }

    @Override
    public void updateByDto(UpdateNoticeDto updateNoticeDto) {

        if(updateNoticeDto.getId() == null ){
            ResultUtil.error(20008,"更新失败，id不能为空");
            return;
        }

        // 先查询数据库获取原始记录
        Notice existingNotice = super.getById(updateNoticeDto.getId());
        if (existingNotice == null) {
            ResultUtil.error(20009,"更新失败，未找到对应记录");
            return;
        }

        // 判断记录是否已被删除
        if(existingNotice.getIsDeleted() == 1){
            ResultUtil.error(20010,"更新失败，该数据已被删除");
            return;
        }
        Notice notice = new Notice();
        BeanUtils.copyProperties(updateNoticeDto, notice);  // DTO到实体的复制

        log.debug("更新数据：{}", notice);
        boolean a = super.updateById(notice);
        log.debug("更新结果：{}", a);

        if(!a){
            ResultUtil.error(20011,"更新失败");
        }
        ResultUtil.success("更新成功");
    }

    @Override
    public List<NoticeListVo> findByNoticeQueryDto(NoticeQueryDto noticeQueryDto) {

        return getMapper().findNoticeByQueryDto(noticeQueryDto);
    }

    @Override
    public String publish(Long id) {

//        Notice notice = super.getById(id);
        Notice notice = new Notice();
        notice.setId(id);
        Long tenantId = Convert.toLong(StpUtil.getExtra("tenant_id"));
        notice.setTenantId(tenantId);
        notice.setStatus("已发布");
        boolean a = super.updateById(notice);
       return a ? "发布成功" : "发布失败";

    }


}
